package xyz.riceball.usercore.utils;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import xyz.riceball.usercore.entity.po.MenuPO;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 树形开发工具类
 * </p>
 *
 * @author xiaovcloud
 * @since 2022/5/1 19:31
 */
public class TreeUtils {

    /**
     * 处理菜单树形结构
     *
     * @param menus 菜单集合
     * @return 菜单树形结构
     */
    public static List<Tree<String>> buildMenu(List<MenuPO> menus) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setWeightKey("weight");
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setChildrenKey("children");
        // 最大递归深度
        treeNodeConfig.setDeep(100);

        return TreeUtil.build(menus, null, treeNodeConfig, (treeNode, tree) -> {
            tree.setId(treeNode.getId());
            tree.setName(treeNode.getName());
            tree.setWeight(treeNode.getWeight());
            tree.setParentId(treeNode.getParentId());
            tree.putExtra("code", treeNode.getCode());
            tree.putExtra("path", treeNode.getPath());
            tree.putExtra("icon", treeNode.getIcon());
            tree.putExtra("type", treeNode.getType());
            tree.putExtra("status",treeNode.getStatus());
            tree.putExtra("remark",treeNode.getRemark());
        });
    }

    /**
     * 接口返回参数
     *
     * @param map
     * @return
     */
    public static List<Tree<String>> buildRoute(List<Map<String, String>> map) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setWeightKey("weight");
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setChildrenKey("children");
        // 最大递归深度
        treeNodeConfig.setDeep(100);

        return TreeUtil.build(map, null, treeNodeConfig, (treeNode, tree) -> {
            tree.setId(treeNode.get("id"));
            tree.setName(treeNode.get("name"));
            tree.setWeight(treeNode.get("weight"));
            tree.setParentId(treeNode.get("parentId"));
            tree.putExtra("code", treeNode.get("code"));
            tree.putExtra("status",treeNode.get("status"));
        });
    }
}
